package com.lhl.jwt.security.config;

import com.lhl.jwt.security.filter.LoginAuthenticationFilter;
import com.lhl.jwt.security.handler.JwtAuthenticationFailureHandler;
import com.lhl.jwt.security.service.JwtUserDetailsService;
import io.swagger.annotations.Api;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;

/**
 * @className: com.lhl.jwt.security.config.LoginConfigurer
 * @description: TODO 类描述
 * @author: king
 * @date: 2020-12-21 18:36
 **/
@Api(tags = "LoginConfigurer", produces = "LoginConfigurer")
public class LoginConfigurer <T extends LoginConfigurer<T, B>, B extends HttpSecurityBuilder<B>>
        extends AbstractHttpConfigurer<T, B> {
    private LoginAuthenticationFilter loginAuthenticationFilter;

    private JwtUserDetailsService jwtUserDetailsService;

    public LoginConfigurer(JwtUserDetailsService jwtUserDetailsService) {
        loginAuthenticationFilter = new LoginAuthenticationFilter();
        this.jwtUserDetailsService = jwtUserDetailsService;
    }

    @Override
    public void configure(B builder) throws Exception {
        loginAuthenticationFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        loginAuthenticationFilter.setJwtUserDetailsService(jwtUserDetailsService);

        loginAuthenticationFilter = postProcess(loginAuthenticationFilter);
        builder.addFilterBefore(loginAuthenticationFilter, LogoutFilter.class);
    }

    public LoginConfigurer<T, B> authenticationSuccessHandler(AuthenticationSuccessHandler successHandler) {
        loginAuthenticationFilter.setAuthenticationSuccessHandler(successHandler);
        return this;
    }

    public LoginConfigurer<T, B> authenticationFailureHandler(JwtAuthenticationFailureHandler jwtAuthenticationFailureHandler) {
        loginAuthenticationFilter.setAuthenticationFailureHandler(jwtAuthenticationFailureHandler);
        return this;
    }
}
